import EXIF from 'exif-js';

// 利用canvas对base64格式数据进行压缩
export const canvasDataURL = (path, quality, fileObj) => {
  return new Promise((resolve, reject) => {
    var img = new Image()
    img.src = path ///base64格式数据
    img.onload = function() {
      var w = this.width * quality,
        h = this.height * quality
      //生成canvas
      var canvas = document.createElement('canvas')
      var ctx = canvas.getContext('2d')
      // 创建属性节点
      var anw = document.createAttribute('width')
      anw.nodeValue = w
      var anh = document.createAttribute('height')
      anh.nodeValue = h
      canvas.setAttributeNode(anw)
      canvas.setAttributeNode(anh)
      // ctx.clearRect(0, 0, w, h);
      EXIF.getData(fileObj, () => {
        var orientation = EXIF.getTag(fileObj, 'Orientation')
        // translate是平移变换，scale(-1,1)是向左翻转，rotate是顺时针旋转。
        // defaultImage.orientation = 6   // 测试iPhone手机
        // alert('Orientation:' + orientation) // 拍照方向
        switch (Number(orientation)) {
          case 2:
            ctx.translate(w, 0)
            ctx.scale(-1, 1)
            ctx.drawImage(img, 0, 0, w, h)
            break
          case 3: //180度旋转
            ctx.rotate((180 * Math.PI) / 180)
            ctx.drawImage(img, -w, -h, w, h)
            // alert(180);
            break
          case 4:
            ctx.translate(w, 0)
            ctx.scale(-1, 1)
            ctx.rotate((180 * Math.PI) / 180)
            ctx.drawImage(img, -w, -h, w, h)
            break
          case 5:
            ctx.translate(w, 0)
            ctx.scale(-1, 1)
            ctx.rotate((90 * Math.PI) / 180)
            ctx.drawImage(img, 0, -w, h, w)
            break
          case 6: //向左90度旋转
            canvas.width = h
            canvas.height = w
            ctx.rotate((90 * Math.PI) / 180)
            ctx.drawImage(img, 0, 0, w, -h)
            // alert(90);
            break
          case 7:
            ctx.translate(w, 0)
            ctx.scale(-1, 1)
            ctx.rotate((270 * Math.PI) / 180)
            ctx.drawImage(img, -h, 0, h, w)
            break
          case 8: //（向右）90度旋转
            ctx.rotate((270 * Math.PI) / 180)
            ctx.drawImage(img, -h, 0, h, w)
            // alert(270);
            break
          default:
            ctx.drawImage(img, 0, 0, w, h)
        }
        // ctx.drawImage(img, 0, 0, w, h);
        var base64 = canvas.toDataURL('image/jpeg', 1)
        console.log('----------------------------------------')
        console.log('改变后:' + base64.length)

        // 回调函数返回base64的值
        resolve(base64);
      })
    }
  });
}

// base64格式转换回二进制图片数据用以上传操作
export const convertBase64UrlToBlob = (urlData) => {
  var arr = urlData.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], {
    type: mime
  })
}

// 利用new FileReader()转换file对象等blob二进制数据成base64格式数据
export const photoCompress = (file) => {
  return new Promise((resolve, reject) => {
    var fileSize = file.size / (1024 * 1024)
    //设定压缩比例
    var quality = 1
    // if (fileSize > 1 && fileSize < 2) {
    //   quality = 0.167;
    // } else if (fileSize >= 2 && fileSize < 3) {
    //   quality = 0.11;
    // } else if (fileSize >= 3 && fileSize < 4) {
    //   quality = 0.0934;
    // } else {
    //   quality = 0.067;
    // }
    if (fileSize > 1 && fileSize < 2) {
      quality = 0.4
    } else if (fileSize >= 2 && fileSize < 3) {
      quality = 0.22
    } else if (fileSize >= 3 && fileSize < 4) {
      quality = 0.1868
    } else {
      quality = 0.134
    }
    var ready = new FileReader()
    /*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
    ready.readAsDataURL(file)
    ready.onloadend = function() {
      var re = this.result //从回调this中获取base64格式数据
      console.log('改变前:' + re.length)
      // 调用压缩
      canvasDataURL(re, quality, file).then(base64 => resolve(base64));
    }
  });
}
